<template>
  <div id="globalHeader">
    <!--:wrap="false" -> 响应式，取消分辨率变小时自动换行-->
    <a-row :wrap="false">

      <!-- logo -->
      <a-col flex="170px">
        <div class="title-bar">
          <img src="../assets/coffee_logo.png" alt="logo" class="logo">
        </div>
      </a-col>

      <!-- 导航栏 -->
      <a-col flex="auto">
        <a-menu
            v-model:selectedKeys="current"
            mode="horizontal"
            :items="items"
            @click="doMenuClick"
        />
      </a-col>

      <!-- 登录按钮 -->
      <a-col flex="300px">
        <div class="user-login-status">
          <div v-if="adminLoginStore.loginUser.userId">
            <div class="user-info">
              <span class="store-name" v-if="storeMsg.storeName">
                <shop-outlined />
                <a-tooltip :title="storeMsg.storeName">
                  <span>{{ storeMsg.storeName }}</span>
                </a-tooltip>
                <a-button 
                  :type="storeMsg.storeStatus === 0 ? 'primary' : 'default'"
                  :danger="storeMsg.storeStatus === 1"
                  size="small"
                  class="store-status-btn"
                  @click="handleStoreStatusChange"
                >
                  {{ storeMsg.storeStatus === 0 ? '打烊' : '开张' }}
                </a-button>
              </span>
              <a-dropdown>
                <div class="user-avatar-info">
                  <a-avatar :size="32" :src="adminLoginStore.loginUser.avatar">
                    {{ adminLoginStore.loginUser.userName?.charAt(0)?.toUpperCase() }}
                  </a-avatar>
                  <span class="username" :title="adminLoginStore.loginUser.userName">{{ adminLoginStore.loginUser.userName ?? '未命名'}}</span>
                </div>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="profile" @click="showProfileModal">
                      <user-outlined />
                      <span>个人信息</span>
                    </a-menu-item>
                    <a-menu-item key="logout" @click="handleLogout">
                      <logout-outlined />
                      <span>退出</span>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
          </div>
          <div v-else>
            <a-button type="primary" @click="showLoginModal">登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- 个人信息弹窗 -->
    <a-modal
      v-model:visible="profileModalVisible"
      title="个人信息"
      @ok="hideProfileModal"
      @cancel="hideProfileModal"
      :footer="null"
    >
      <div class="profile-container">
        <div class="profile-avatar">
          <a-avatar :size="64" :src="adminLoginStore.loginUser.avatar">
            {{ adminLoginStore.loginUser.userName?.charAt(0)?.toUpperCase() }}
          </a-avatar>
        </div>
        <div class="profile-info">
          <div class="profile-item">
            <span class="profile-label">用户名：</span>
            <template v-if="!isEditing">
              <span class="profile-value">{{ adminLoginStore.loginUser.userName }}</span>
            </template>
            <template v-else>
              <a-input v-model:value="formState.userName" placeholder="请输入用户名" />
            </template>
          </div>
          <div class="profile-item">
            <span class="profile-label">用户ID：</span>
            <span class="profile-value">{{ adminLoginStore.loginUser.userId }}</span>
          </div>
          <div class="profile-item">
            <span class="profile-label">手机号：</span>
            <span class="profile-value">{{ adminLoginStore.loginUser.phone }}</span>
          </div>
        </div>
        <div class="profile-actions">
          <template v-if="!isEditing">
            <a-button type="primary" @click="handleEditProfile">
              <edit-outlined /> 编辑
            </a-button>
          </template>
          <template v-else>
            <a-button type="primary" @click="handleSaveProfile" style="margin-right: 8px;">
              <check-outlined /> 保存
            </a-button>
            <a-button @click="isEditing = false">
              <close-outlined /> 取消
            </a-button>
          </template>
        </div>
      </div>
    </a-modal>

    <!-- 登录弹窗 -->
    <LoginModal ref="loginModalRef" />
  </div>

</template>
<script lang="ts" setup>
import { h, ref, reactive } from 'vue';
import {
  HomeOutlined,
  AppstoreOutlined,
  SettingOutlined,
  CrownOutlined,
  UserOutlined,
  EditOutlined,
  CheckOutlined,
  CloseOutlined,
  LogoutOutlined,
  TagsOutlined,
  ToolOutlined,
  ShoppingOutlined,
  FileTextOutlined,
  SafetyCertificateOutlined,
  ShopOutlined
} from '@ant-design/icons-vue';
import { MenuProps, message } from 'ant-design-vue';
import { useRouter } from "vue-router";
import { editUser } from "@/api/user";
import { listPermission } from '@/api/permission';
import LoginModal from './LoginModal.vue';
import {useAdminLoginStore} from "@/store/useAdminLoginUserStore";
import {useStoreMsgStore} from "@/store/useStoreMsgStore";
import { close, open } from '@/api/store';

const adminLoginStore = useAdminLoginStore();
const router = useRouter();
const loginModalRef = ref();
// 控制个人信息弹窗的显示
const profileModalVisible = ref(false);
// 控制是否处于编辑状态
const isEditing = ref(false);
// 表单数据
const formState = reactive({
  userName: ''
});
// 门店信息
const storeMsg = useStoreMsgStore();

// 显示个人信息弹窗
const showProfileModal = () => {
  profileModalVisible.value = true;
  // 重置编辑状态
  isEditing.value = false;
  // 初始化表单数据
  formState.userName = adminLoginStore.loginUser.userName || '';
};

// 关闭个人信息弹窗
const hideProfileModal = () => {
  profileModalVisible.value = false;
  // 重置编辑状态
  isEditing.value = false;
};

// 路由跳转事件
const doMenuClick = ({ key }: { key: string }) => {
  router.push({ path: key }).catch(err => {
    console.error('路由跳转失败:', err);
  });
}

// 导航栏当前值（导航栏高亮显示当前菜单）
const current = ref<string[]>(['/']);
router.afterEach((to) => {
  console.log('路由变化:', to.path);
  current.value = [to.path];
});

// 显示登录弹窗
const showLoginModal = () => {
  loginModalRef.value.show();
};

// 菜单项
const items = ref<MenuProps['items']>([]);

const navItemMap: { [key: string]: NonNullable<MenuProps['items']>[number] } = {
  'adminHome': {
    key: '/admin/adminHome',
    icon: () => h(HomeOutlined),
    label: '主页',
    title: '主页',
  },
  'Store_Manage': {
    key: '/admin/store',
    icon: () => h(SettingOutlined),
    label: '门店管理',
    title: '门店管理',
  },
  'Category_Manage': {
    key: '/admin/category',
    icon: () => h(TagsOutlined),
    label: '分类管理',
    title: '分类管理',
  },
  'Product_Manage': {
    key: '/admin/product',
    icon: () => h(ShoppingOutlined),
    label: '商品管理',
    title: '商品管理',
  },
  'Product_Setting': {
    key: '/admin/product-config',
    icon: () => h(AppstoreOutlined),
    label: '商品配置',
    title: '商品配置',
  },
  'Param_Manage': {
    key: '/admin/param',
    icon: () => h(ToolOutlined),
    label: '参数管理',
    title: '参数管理',
  },
  'Template_Manage': {
    key: '/admin/template',
    icon: () => h(CrownOutlined),
    label: '模板管理',
    title: '模板管理',
  },
  'Store_Order': {
    key: '/admin/store-orders',
    icon: () => h(FileTextOutlined),
    label: '门店订单',
    title: '门店订单',
  },
  'Permission_Manage': {
    key: '/admin/permission',
    icon: () => h(SafetyCertificateOutlined),
    label: '权限管理',
    title: '权限管理',
  },
  'Employee_Manage': {
    key: '/admin/employee',
    icon: () => h(SafetyCertificateOutlined),
    label: '人员管理',
    title: '人员管理',
  },
  'Role_Manage': {
    key: '/admin/role',
    icon: () => h(SafetyCertificateOutlined),
    label: '角色管理',
    title: '角色管理',
  }
};

// 调用接口获取导航项
const fetchNavItems = async () => {
  try {
    const res = await listPermission();
    console.log('权限接口返回数据:', res.data.data);
    if (res.data.code === 200) {
      const havaStore = res.data.data.havaStore;
      if(havaStore === false) {
        router.replace('/empty');
        return;
      }

      const storeId = res.data.data.storeId;
      storeMsg.setStoreId(storeId);

      const storeName = res.data.data.storeName;
      console.log('获取到的门店名称:', storeName);
      storeMsg.setStoreName(storeName);

      const isPublicStore = res.data.data.isPublicStore;
      storeMsg.setIsPublicStore(isPublicStore);

      const storeStatus = res.data.data.storeStatus;
      storeMsg.setStoreStatus(storeStatus);

      const permissionList = res.data.data.permissionList;
      items.value = permissionList.map((key: string) => navItemMap[key] || null).filter(Boolean);
    }
  } catch (error) {
    console.error('获取导航项失败:', error);
  }
};

// 初始化时调用
fetchNavItems();

// 处理编辑个人信息
const handleEditProfile = () => {
  isEditing.value = true;
};

// 处理保存个人信息
const handleSaveProfile = async () => {
  try {
    // 调用编辑用户信息的API
    const res = await editUser({
      userName: formState.userName
    });

    if (res.data.code === 200) {
      // 更新本地用户信息
      adminLoginStore.loginUser.userName = formState.userName;
      message.success('保存成功');
      // 退出编辑状态
      isEditing.value = false;
    } else {
      message.error(res.data.msg || '保存失败');
    }
  } catch (error) {
    console.error('保存个人信息失败:', error);
    message.error('保存失败，请稍后重试');
  }
};

// 处理退出登录
const handleLogout = () => {
  // 跳转到登录页
  router.push('/adLogin');
  // 清除本地存储的token
  localStorage.removeItem('adminToken');
  // 清除用户信息
  adminLoginStore.loginUser = {};
};

// 处理门店状态变更
const handleStoreStatusChange = async () => {
  try {
    const res = storeMsg.storeStatus === 0 
      ? await close(storeMsg.storeId)
      : await open(storeMsg.storeId);

    if (res.data.code === 200) {
      // 更新状态
      storeMsg.setStoreStatus(storeMsg.storeStatus === 0 ? 1 : 0);
      message.success(storeMsg.storeStatus === 0 ? '已开张' : '已打烊');
    } else {
      message.error(res.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('更改门店状态失败:', error);
    message.error('操作失败，请稍后重试');
  }
};
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center; /*垂直居中*/
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.user-avatar-info:hover {
  background-color: rgba(0, 0, 0, 0.04);
}

.store-name {
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 4px;
  padding-right: 16px;
  border-right: 1px solid #e8e8e8;
  max-width: 200px;
}

.store-name .anticon {
  font-size: 14px;
  flex-shrink: 0;
}

.store-name span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.username {
  font-size: 14px;
  color: #333;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.profile-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.profile-avatar {
  margin-bottom: 20px;
}

.profile-info {
  width: 100%;
}

.profile-item {
  margin-bottom: 12px;
  display: flex;
}

.profile-label {
  font-weight: bold;
  width: 80px;
  color: #666;
}

.profile-value {
  color: #333;
}

.profile-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.user-login-status {
  display: flex;
  justify-content: flex-end;
  padding-right: 24px;
}

.store-status {
  margin-left: 8px;
  font-size: 12px;
  padding: 0 8px;
  border-radius: 4px;
}

.store-status-btn {
  margin-left: 8px;
  font-size: 12px;
  height: 24px;
  padding: 0 12px;
  flex-shrink: 0;
}
</style>


